const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: -1,
    mode: '',
    dateVisible: false,
    date: new Date().getTime(), // 支持时间戳传入
    dateText: '',
    // 指定选择区间起始值
    start: '2024-01-01 00:00:00',
    end: '2099-09-09 12:12:12',
    filter(type, options) {
      if (type === 'year') {
        return options.sort((a, b) => b.value - a.value);
      }
      return options;
    },
    popupProps: {
      usingCustomNavbar: true,
    },
    autosize: {
      maxHeight: 120,
      minHeight: 20,
    },
    shareSize: '0 人',
    positionVisible: false,
    dicPositionList: [],
    //日记对象
    notebook: {},
    typeText: "",
    typeValue: '',
    originFiles: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    config: {
      count: 1,
    },
    shareIdList: [],
    notebookContent: "",
    switchDefaultVal: false,
    switchDisStatus: true,
    titleHidden: false,
    publishTitle: ''
  },

  //改变开关值
  handleSwitchChange(e) {
    const titleHiddenFlag = e.detail.value;
    this.setData({
      switchDefaultVal: e.detail.value,
      titleHidden: titleHiddenFlag
    });
  },

  //发布标题改变事件
  inputPublishTitle: function (e) {
    const value = e.detail.value;
    this.setData({
      publishTitle: value
    })
  },

  //变更了选中项
  setSelectSize: function () {
    let that = this;
    let selectList = that.data.shareIdList;
    console.log("setSelectSize:" + selectList)
    if (undefined != selectList) {
      that.setData({
        shareSize: selectList.length + " 人"
      })
    }
  },

  //选择文件完成
  handleAdd: function (e) {
    console.log("handleAdd 事件")
    let baseUrl = httpUtils.getBaseUrl();
    let that = this;
    const {
      files
    } = e.detail;
    console.log("files:" + JSON.stringify(files))
    wx.showLoading({
      title: '图片上传中.....',
    });
    let completeNum = 0;
    for (let index = 0; index < files.length; index++) {
      const uploadFilePromise = new Promise(function (resolve, reject) {
        wx.uploadFile({
          filePath: files[index].url,
          name: 'file',
          url: baseUrl + '/file/miniUpload',
          formData: {},
          header: {
            'Content-Type': 'application/json',
            'X-Access-Token': wx.getStorageSync('token')
          },
          success: (res) => {
            console.log(res)
            if (res.statusCode == 200) {
              resolve(res.data);
            }
          }
        })
      });
      // 等待上传完成后执行其他操作
      uploadFilePromise.then(function (result) {
        // 在这里可以执行上传完成后的逻辑
        console.log('文件上传成功，返回结果：', result);
        completeNum++;
        const arr = result.split("/");
        let fileName = arr[arr.length - 1];
        let file = {
          url: result,
          name: fileName,
          type: "image"
        }
        that.data.originFiles.push(file);
        that.setData({
          originFiles: that.data.originFiles
        });
        if (completeNum == files.length) {
          wx.hideLoading();
        }
      });
    }
  },

  //点击删除事件
  handleRemove(e) {
    console.log("handleRemove 事件")
    const {
      index
    } = e.detail;
    const {
      originFiles
    } = this.data;
    originFiles.splice(index, 1);
    this.setData({
      originFiles,
    });
  },

  //点击图片
  handleClick(e) {
    console.log("handleClick 事件")
    console.log(e.detail.file);
  },

  //选择共享用户
  clickShareUser() {
    console.log('点击了共享用户');
    wx.navigateTo({
      url: '/pages/my-pages/select-share-user/index',
    })
  },

  //多行文本框改变行
  onLineChange: function (e) {
    console.log('lineCount: ', e.detail);
  },

  //显示日期选择器
  showPicker: function (e) {
    const {
      mode
    } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },

  //隐藏日期选择器
  handleClose(e) {
    console.log('handleClose:', e);
  },

  //选中日期点击确定
  onConfirm(e) {
    const {
      value
    } = e.detail;
    const {
      mode
    } = this.data;
    console.log('confirm', value);
    this.setData({
      [mode]: value,
      [`${mode}Text`]: value,
    });
  },

  //改变日期选择器的值
  onColumnChange(e) {
    console.log('pick', e.detail.value);
  },

  //时间格式化
  formaData: function (timer) {
    let that = this;
    const year = timer.getFullYear()
    const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
    const day = timer.getDate()
    return `${that.pad(year, 4)}-${that.pad(month)}-${that.pad(day)}`
  },

  // 定义具体处理标准
  // timeEl 传递过来具体的数值：年月日时分秒
  // total 字符串总长度 默认值为2
  // str 补充元素 默认值为"0"
  pad: function (timeEl, total = 2, str = '0') {
    return timeEl.toString().padStart(total, str)
  },

  //打开日记类型弹窗
  onPositionPicker: function (e) {
    let that = this;
    that.setData({
      positionVisible: true,
    });
  },
  //日记类型弹窗点击取消按钮
  onPickerCancel: function (e) {
    this.setData({
      positionVisible: false,
    })
  },

  //日记类型改变
  onPickerChange: function (e) {
    const {
      value
    } = e.detail;
    console.log("label : " + e.detail.label)
    console.log("value : " + e.detail.value)
    console.log("选择: value[0] = " + value[0])
    this.setData({
      typeText: e.detail.label,
      typeValue: value[0]
    })
  },

  //多行文本框输入改变事件
  inputContent: function (e) {
    this.setData({
      notebookContent: e.detail.value
    })
  },

  //查询日记类型字典
  getDicList: function () {
    let obj = {
      method: 'GET',
      showLoading: false,
      url: 'dic/miniProjectDicList?parentId=1868907376092954626'
    }
    httpUtils.request(obj).then(res => {
      console.log(res.data.message)
      if (res.data.retCode == 0) {
        this.setData({
          dicPositionList: res.data.data
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  //获取我的配置
  getMyConfigFlag: function () {
    let that = this;
    let obj = {
      method: 'GET',
      showLoading: false,
      url: 'weChatDev/getMyConfigStatus'
    }
    httpUtils.request(obj).then(res => {
      console.log(res.data.message)
      if (res.data.retCode == 0) {
        // console.log('用户信息: ' + res.data.data)
        that.setData({
          switchDisStatus: !res.data.data,
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  //点击了保存
  confirmSaveButton: function () {
    let that = this;
    let obj;
    let fileList = that.data.originFiles;
    let fileUrlList = [];
    if (undefined != fileList && 'null' != fileList && fileList.length > 0) {
      for (let index = 0; index < fileList.length; index++) {
        fileUrlList.push(fileList[index].url);
      }
    }
    obj = {
      method: 'POST',
      showLoading: true,
      url: 'notebook/addNotebook',
      data: {
        // 'recordDate': that.data.dateText,
        'recordTypeDic': that.data.typeValue,
        'content': that.data.notebookContent,
        'shareIdList': that.data.shareIdList,
        'imagesFiles': fileUrlList,
        'publishWechatFlag': that.data.switchDefaultVal,
        'publishTitle': that.data.publishTitle
      }
    }
    httpUtils.request(obj).then(res => {
      if (res.data.retCode == 0) {
        ui.showToast('保存成功')
        wx.navigateBack({
          detail: 1
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getMyConfigFlag();
    this.getDicList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    that.setData({
      dateText: that.formaData(new Date()),
    })
    this.setSelectSize();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})